package com.xinhua.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    private static DataSource dataSource=null;
    //加载驱动
    public static void load(){
        Properties properties=new Properties();
        try {
            InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(resourceAsStream);
            dataSource= DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static Connection getConnection()throws Exception{
        load();
        return dataSource.getConnection();
    }
    //
    public static DataSource getDataSource(){
        load();
        return dataSource;
    }
    public static void release(ResultSet resultSet, Statement statement, Connection connection) {
        // 资源释放：
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            resultSet = null;
        }
        if(statement != null){
            try {
                statement.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            statement = null;
        }
        if(connection != null){
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            connection = null;
        }
    }

    public static void release(PreparedStatement statement, Connection connection) {

        if(statement != null){
            try {
                statement.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            statement = null;
        }
        if(connection != null){
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            connection = null;
        }
    }
}
